<template>
  <div class="about">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
    <el-breadcrumb-item :to="{path:'/blank'}"><i class="el-icon-user-solid"></i>系统管理</el-breadcrumb-item>
    <el-breadcrumb-item :to="{path:'/user'}">用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加用户</el-breadcrumb-item>
  </el-breadcrumb>
    <el-divider></el-divider>
    <el-card style="margin: 0 auto;width: 600px">
      <h1 style="font-size: 20px">添加用户</h1>
      <el-form :model="user" ref="ruleForm"  :rules="rules" label-width="100px" style="margin: 10px 0">
        <el-form-item label="用户名" prop="username">
          <el-input type="text" placeholder="账号" prefix-icon="el-icon-user" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="密码" prefix-icon="el-icon-lock" v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="trueName">
          <el-input type="text" placeholder="真实姓名" prefix-icon="el-icon-user" v-model="user.trueName"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input type="text" placeholder="电话" prefix-icon="el-icon-phone" v-model="user.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" placeholder="邮箱" prefix-icon="el-icon-s-platform" v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="班级专业" prop="majorId">
          <template>
            <div style="text-align: left">
              <el-select v-model="user.majorId" :value="user.majorId" placeholder="请选择专业" @change="getClassArr">
                <el-option v-for="item in majorArr" :label="item.majorName" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <template>
            <div style="text-align: left">
              <el-select v-model="user.classId" :value="user.classId" placeholder="请选择班级">
                <el-option v-for="item in classArr" :label="item.className" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="角色" prop="roleId" >
          <template>
            <div style="text-align: left">
              <el-select v-model="user.roleId" :value="user.roleId" placeholder="请选择角色">
                <el-option v-for="item in roleArr" :label="item.roleName" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </div>
          </template>
        </el-form-item>
        <el-form-item style="float: left">
          <el-button type="primary" @click="submitUserAdd('ruleForm')">添加</el-button>
          <el-button type="warning" @click="goUserList">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
 data(){
   return{
     user: {
       username: '',
       password: '',
       trueName:'',
       phone:'',
       email:'',
       majorId:'',
       classId:'',
       className:'',
       majorName:'',
       roleId:''
     },
     roleArr:[],
     majorArr: [],
     classArr:[],
     rules: {
       username: [
         { required: true, message: '请输入用户名', trigger: 'blur' },
         { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' }
       ],
       password: [
         { required: true, message: '请输入密码', trigger: 'blur' },
         { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
         {pattern:/^([1-9A-Za-z]*)$/,message:'请输入以字母和数字组成的密码',trigger: 'blur'}
       ],
       trueName: [
         { required: true, message: '请输入真实姓名', trigger: 'blur' },
         {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
       ],
       phone:[
         { required: true, message: '请输入电话', trigger: 'blur' },
         {pattern:/^1\d{10}$/,message:'请输入正确的电话',trigger: 'blur'}
       ],
       email:[
         { required: true, message: '请输入邮箱', trigger: 'blur' },
         /*^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$*/
         {pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,message:'请输入邮箱',trigger: 'blur'}
       ],
       majorId:[
         { required: true, message: '专业不能为空', trigger: 'blur' }
       ],
       classId:[
         { required: true, message: '班级不能为空', trigger: 'blur' }
       ],
       roleId:[
         { required: true, message: '班级不能为空', trigger: 'blur' }
       ]
     }
   }
 },
  methods:{
    goUserList(){
      this.$router.push('/user')
    },
    submitUserAdd(formName){
      this.$refs[formName].validate((valid) => {
        if(valid){
          let url = 'http://localhost:9281/user-add-new';
          console.log(url);
          let userJson = JSON.stringify(this.user);
          localStorage.setItem("userJson",userJson);
          let jwt = localStorage.getItem("localJwt");
          for (let i = 0; i < this.majorArr.length; i++) {
            if(this.majorArr[i].id==this.user.majorId){
              this.user.majorName = this.majorArr[i].majorName;
            }
          }

          for (let i = 0; i < this.classArr.length; i++) {
            if(this.classArr[i].id==this.user.classId){
              this.user.className = this.classArr[i].className;
            }
          }
          let formData = this.qs.stringify(this.user);
          console.log(formData)
          this.axios
              .create({
                'headers':{
                  'Authorization':jwt
                }
              })
              .post(url,formData).then((response)=>{
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                showClose: true,
                message: '注册成功',
                type: 'success'
              });
              this.$router.push('/user')
              if (jsonResult.jwt!=null){
                localStorage.setItem("localJwt",jsonResult.jwt);
              }
            }else if(jsonResult.state==70100){
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
              this.$router.push('/')
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })
        }else {
          console.log('error submit!!');
          return false;
        }


      })
    },
    getRoleArr(){
      let url = 'http://localhost:9281/userRole/list-input';
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .get(url).then((response)=>{
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.roleArr = jsonResult.data;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    getMajorArr(){
      let url = "http://localhost:9281/major/list";
      console.log(url);
      this.axios.get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.majorArr = jsonResult.data;
        }else{
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
          });
        }
      })
    },
    getClassArr(){
      this.user.classId = null;
      this.user.className = null;
      console.log(this.user)
      let url = "http://localhost:9281/class/list?id="+this.user.majorId;
      let jwt = localStorage.getItem("localJwt");
      console.log(url);
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.classArr = jsonResult.data;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else{
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    LoadLocalUser(){
      let userJson = localStorage.getItem("userJson");
      if(userJson!=null){
        this.user = JSON.parse(userJson);
        this.user.majorId = null;
        this.user.majorName = null;
        this.user.classId = null;
        this.user.className = null;
      }
    }

  },
  mounted() {
    this.getMajorArr();
    this.getRoleArr();
    //this.getClassArr();
    this.LoadLocalUser();
  }

}
</script>
